package com.yiper.security;

import com.yiper.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * @version V1.0
 * @date 2018年8月8日
 * @author yiper
 */
public class PasswordHelper {

    private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    private static String algorithmName = "md5";
    private static final int hashIterations = 2;

    public static void encryptPassword(User user) {

        user.setSalt(randomNumberGenerator.nextBytes().toHex());

        String newPassword = new SimpleHash(
                algorithmName,
                user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),
                hashIterations).toHex();

        user.setPassword(newPassword);
    }

    /**
     * <p class="detail">
     * 功能:使用salt（随机数）+用户名进行2次MD5加密
     * </p>
     *
     * @param user :
     * @return string
     * @author yiper
     * @date 2017.07.17 17:26:55
     */
    public static String getPassword(User user){
        String encryptPassword = new SimpleHash(
                algorithmName,user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()),
                hashIterations)
                .toHex();
        return encryptPassword;
    }
}
